<?php
/**
 * tinymvc超轻量级PHP开发框架
 *
 * @author    Lansn
 * @copyright Copyright (c) 2024-2025
 * @license   tinymvc 遵循Apache2开源协议发布，需保留开发者信息。
 * @link      http://173654757.xyz
 */

namespace system\core;

use Flight;

class Lang
{
    protected static string $language = 'zh_cn';
    protected static array $data = [];

    public static function init(string $module): void
    {
        $config = config('app');
        $default = $config['default_language'] ?? 'zh_cn';

        // 检测浏览器语言
        $browserLang = strtolower(substr($_SERVER['HTTP_ACCEPT_LANGUAGE'] ?? '', 5));
        $langMap = [
            'zh-cn' => 'zh_cn',
            'en-us' => 'en_us'
        ];
        $chosenLang = $langMap[$browserLang] ?? $default;
        self::$language = in_array($chosenLang, $config['supported_languages'] ?? []) ? $chosenLang : $default;

        // 使用 Flight 缓存语言数据，key 带模块名防止跨模块污染
        $cacheKey = "lang.{$module}." . self::$language;
        $cachedData = Flight::get($cacheKey);

        if (is_array($cachedData)) {
            self::$data = $cachedData;
            return;
        }

        // 加载语言文件
        $langFile = APP_PATH . "$module/language/" . self::$language . '.php';
        if (file_exists($langFile)) {
            self::$data = include $langFile;
            Flight::set($cacheKey, self::$data);
        } else {
            self::$data = [];
            Flight::set($cacheKey, []);
        }
    }

    public static function get(string $key, $default = ''): string
    {
        return self::$data[$key] ?? $default;
    }

    public static function all(): array
    {
        return self::$data;
    }

    public static function current(): string
    {
        return self::$language;
    }
}

